package org.sjs.dreamfly.data

import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Update
import org.sjs.dreamfly.common.util.LogUtil
import org.sjs.dreamfly.model.HistoryItem
import org.sjs.dreamfly.model.MovieInfo
import org.sjs.dreamfly.model.ResourceType

@Dao
interface HistoryItemDao {
    @Query("SELECT * FROM history_item")
    fun loadAll(): List<HistoryItem>
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insert(historyItem: HistoryItem)

    @Query("SELECT * FROM history_item WHERE resourceType = :resourceType AND resourceId = :resourceId")
    suspend fun query(@ResourceType resourceType: Int, resourceId: String): List<HistoryItem>

    suspend fun updateOrInsert(historyItem: HistoryItem) {
        query(historyItem.resourceType, historyItem.resourceId).firstOrNull().let {
            if (it != null) {
                LogUtil.d("id:${it.id} ${it.title} is existed")
                historyItem.id = it.id
            }
            insert(historyItem)
        }
    }
}

